package com.example.administrator.hqq.service;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;

import com.example.administrator.hqq.MainActivity;
import com.example.administrator.hqq.R;
import com.example.administrator.hqq.base.MyApplication;
import com.example.administrator.hqq.bean.Complain;
import com.example.administrator.hqq.bean.GroupEvent;
import com.example.administrator.hqq.bean.UmengNotificationBean;
import com.example.administrator.hqq.bean.event.InformationEvent;
import com.example.administrator.hqq.config.LoongsConfig;
import com.example.administrator.hqq.utils.VoiceAndVIbratorUtils;
import com.google.gson.Gson;

import org.apache.commons.codec.binary.Base64;
import org.eclipse.paho.android.service.MqttAndroidClient;
import org.eclipse.paho.client.mqttv3.DisconnectedBufferOptions;
import org.eclipse.paho.client.mqttv3.IMqttActionListener;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.IMqttMessageListener;
import org.eclipse.paho.client.mqttv3.IMqttToken;
import org.eclipse.paho.client.mqttv3.MqttCallbackExtended;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.nio.charset.Charset;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

import io.rong.imkit.RongIM;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;

import static com.example.administrator.hqq.bean.GroupEvent.Type.ALTER_GROUP;
import static org.eclipse.paho.client.mqttv3.MqttConnectOptions.MQTT_VERSION_3_1_1;

/**
 * MQTT消息服务
 * Created by HongYuLiu on 2018/4/9.
 */

public class AppMqttService extends Service {
    //服务器地址
    final String serverUri = "tcp://mqtt-cn-0pp10tegi02.mqtt.aliyuncs.com:1883";
    final String groupId = "GID_app_1";
    //订阅的topic
    final String topic = "HQQ_APP_NOTIFICATION";
    final Boolean cleanSession =false;
    String instanceId="mqtt-cn-0pp10tegi02";
    String clientId = groupId+ "@@@"+ LoongsConfig.getUser_id();
    String accessKey = "LTAIW690HSRuiWsr";
    String secretKey = "YwYeLbmcUkxqh7S8YVkLeYvMkufuom";
    String TAG=this.getClass().getSimpleName();


    MqttAndroidClient mqttAndroidClient;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;

    }

    @Override
    public void onCreate() {
        super.onCreate();
        EventBus.getDefault().register(this);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        mqttAndroidClient = new MqttAndroidClient(getApplicationContext(), serverUri, clientId);
        mqttAndroidClient.setCallback(new MqttCallbackExtended() {
            @Override
            public void connectComplete(boolean reconnect, String serverURI) {
                if (reconnect) {
                    Log.e(TAG, "重新连接connectComplete: ");
                    subscribeToTopic();
                } else {
                }
                Log.e(TAG, "重新连接完成connectComplete: ");
            }

            @Override
            public void connectionLost(Throwable cause) {
                if (cause!=null)
                {
                    Log.e("AppMqttService","连接失败信息"+cause.toString());
                }else{
                    Log.e("AppMqttService","断开连接");
                }
            }

            @Override
            public void messageArrived(String topic, MqttMessage message) throws Exception {
                Log.e(TAG,"接收的消息Incoming message: " + new String(message.getPayload()));
                disposeMqttMessage(new String(message.getPayload()));
            }

            @Override
            public void deliveryComplete(IMqttDeliveryToken token) {

            }
        });
        MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();
        String sign = null;
        try {
            sign = macSignature(clientId, secretKey);
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        Log.e(TAG, "sign: "+sign );
        Log.e("TAG", "onCreate: "+"Signature"+"|"+accessKey+"|"+instanceId );
        mqttConnectOptions.setUserName("Signature"+"|"+accessKey+"|"+instanceId);
        mqttConnectOptions.setPassword(sign.toCharArray());
        mqttConnectOptions.setCleanSession(cleanSession);
        mqttConnectOptions.setKeepAliveInterval(90);
        mqttConnectOptions.setAutomaticReconnect(true);
        mqttConnectOptions.setMqttVersion(MQTT_VERSION_3_1_1);
        try {
            //addToHistory("Connecting to " + serverUri)
            mqttAndroidClient.connect(mqttConnectOptions, null, new IMqttActionListener() {
                @Override
                public void onSuccess(IMqttToken asyncActionToken) {
                    DisconnectedBufferOptions disconnectedBufferOptions = new DisconnectedBufferOptions();
                    disconnectedBufferOptions.setBufferEnabled(true);
                    disconnectedBufferOptions.setBufferSize(100);
                    disconnectedBufferOptions.setPersistBuffer(false);
                    disconnectedBufferOptions.setDeleteOldestMessages(false);
                    mqttAndroidClient.setBufferOpts(disconnectedBufferOptions);
                    subscribeToTopic();
                    Log.e(TAG, "链接成功onSuccess: ");
                }

                @Override
                public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
//                    addToHistory("Failed to connect to: " + serverUri);
                    Log.e(TAG,"链接失败+++"+exception.toString());
                }
            });
        } catch (MqttException ex){
            ex.printStackTrace();
        }
        return START_STICKY;
    }

    /**
     * 融云删除本地对话列表
     * @param type
     * @param id
     */
    public static void  removeRongyunConversation(Conversation.ConversationType type,String id){
        //删除本地消息缓存
        RongIM.getInstance().clearMessages(type, id, new RongIMClient.ResultCallback<Boolean>() {
            @Override
            public void onSuccess(Boolean aBoolean) {

            }

            @Override
            public void onError(RongIMClient.ErrorCode errorCode) {

            }
        });
        //删除本地对话框
        RongIM.getInstance().removeConversation(type
                , id,new RongIMClient.ResultCallback<Boolean>() {
                    @SuppressLint("LongLogTag")
                    @Override
                    public void onSuccess(Boolean aBoolean) {
                        Log.e("removeRongyunConversation", "onSuccess: "+aBoolean );
                    }

                    @SuppressLint("LongLogTag")
                    @Override
                    public void onError(RongIMClient.ErrorCode errorCode) {
                        Log.e("removeRongyunConversation", "onError: "+errorCode );

                    }
                });
    }

    /**
     * 显示消息推送
     * @param context
     * @param umengNotificationBean
     */
    private void showNotification(Context context, UmengNotificationBean umengNotificationBean) {
        Intent intent = new Intent(this, MainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.putExtra(LoongsConfig.type,umengNotificationBean.getType());
        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
        NotificationManager manger = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
        Notification.Builder builder1 = new Notification.Builder(context);
        builder1.setContentTitle(umengNotificationBean.getTitle());//设置标题，必要
        builder1.setContentText(umengNotificationBean.getText());//设置内容，必要
        builder1.setWhen(System.currentTimeMillis());//设置时间，默认设置，可以忽略
        builder1.setSmallIcon(R.mipmap.logo);//设置通知栏的小图标，必须设置
        builder1.setAutoCancel(true);//设置自动删除，点击通知栏信息之后系统会自动将状态栏的通知删除，要与setContentIntent连用
        builder1.setContentIntent(pendingIntent);
        builder1.setTicker("new message");// 第一次提示消失的时候显示在通知栏上的
        builder1.setOngoing(true);
        builder1.setNumber(20);
        Notification build = builder1.build();
        if ("NOTIFICATION".equals(umengNotificationBean.getType()))
        {
            manger.notify(LoongsConfig.MessageNotification.messageNotificationId, build);//通知消息id为2
        }
        else{
            manger.notify(3, build);//回复消息id为3
        }
    }

    public void subscribeToTopic() {
        try {
            mqttAndroidClient.subscribe(topic, 1, null, new IMqttActionListener() {
                @Override
                public void onSuccess(IMqttToken asyncActionToken) {
                    //addText("Subscribed!");
                    Log.e(TAG, "订阅成功");
                }

                @Override
                public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
                    //addText("Failed to subscribe");
                    Log.e(TAG, "订阅失败"+exception.getMessage());
                }
            });
            mqttAndroidClient.subscribe(topic, 1, new IMqttMessageListener() {
                @Override
                public void messageArrived(String topic, MqttMessage message) throws Exception {
                    Log.e(TAG, "Message " + topic + ":" + new String(message.getPayload()));
                    disposeMqttMessage(new String(message.getPayload()));
                }
            });
        } catch (Exception ex) {
            Log.e("", ex.toString());
        }
    }

    private void disposeMqttMessage(String custom) {
        Gson gson = new Gson();
        UmengNotificationBean umengNotificationBean = gson.fromJson(custom, UmengNotificationBean.class);
        if ("REFRESH".equals(umengNotificationBean.getType()))
        {
            //更新联系人列表
            updateContactsList();
            return;
        }else if ("FORCED_OUT_DIRECTCHAT".equals(umengNotificationBean.getType()))
        {
            //删除联系人
            removeRongyunConversation(Conversation.ConversationType.PRIVATE,umengNotificationBean.getTarget_id());
            //更新联系人列表
            updateContactsList();
            return;
        } else if ("FORCED_OUT_GROUP".equals(umengNotificationBean.getNotice_type())) {
            //删除群聊
            removeRongyunConversation(Conversation.ConversationType.GROUP,umengNotificationBean.getGroup_id());
            //更新联系人列表
            updateContactsList();
        }
        //关于消息与通知的提示
        if ("NOTIFICATION".equals(umengNotificationBean.getType()))
        {
            int Number = LoongsConfig.getUsersIdSPUtils().getInt(LoongsConfig.MessageNotification.InformationNotificationNumber, 0);
            Number++;
            LoongsConfig.getUsersIdSPUtils().put(LoongsConfig.MessageNotification.InformationNotificationNumber,Number);
            showNotificationAndUpdateInformationList(umengNotificationBean);
        }
        else{
            int Number = LoongsConfig.getUsersIdSPUtils().getInt(LoongsConfig.MessageNotification.InformationMessageNumber, 0);
            Number++;
            LoongsConfig.getUsersIdSPUtils().put(LoongsConfig.MessageNotification.InformationMessageNumber,Number);
            showNotificationAndUpdateInformationList(umengNotificationBean);
        }
    }

    /**
     * 发送通知并且更新消息列表页
     * @param umengNotificationBean
     */
    public void showNotificationAndUpdateInformationList(UmengNotificationBean umengNotificationBean){
        if (LoongsConfig.getUsersIdSPUtils().getBoolean(LoongsConfig.MessageNotification.messageNotification,true))
        {
            if (!MyApplication.isFront())
            showNotification(getApplication(),umengNotificationBean);
            try {
                VoiceAndVIbratorUtils.playVoice(getApplication());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        InformationEvent informationEvent = new InformationEvent();
        informationEvent.setType(umengNotificationBean.getType());
        EventBus.getDefault().post(informationEvent);
    }

    /**
     * 更新联系人列表
     */
    public void updateContactsList(){
        GroupEvent groupEvent = new GroupEvent();
        groupEvent.setType(ALTER_GROUP);
        EventBus.getDefault().post(groupEvent);
    }
    /**
     * @param text      要签名的文本
     * @param secretKey 阿里云MQ secretKey
     * @return 加密后的字符串
     * @throws InvalidKeyException
     * @throws NoSuchAlgorithmException
     */
    public static String macSignature(String text, String secretKey) throws InvalidKeyException, NoSuchAlgorithmException {
        Charset charset = Charset.forName("UTF-8");
        String algorithm = "HmacSHA1";
        Mac mac = Mac.getInstance(algorithm);
        mac.init(new SecretKeySpec(secretKey.getBytes(charset), algorithm));
        byte[] bytes = mac.doFinal(text.getBytes(charset));
        return new String(Base64.encodeBase64(bytes), charset);
    }

    @Override
    public void onDestroy() {
        if (mqttAndroidClient != null) {
            if (mqttAndroidClient.isConnected()) {
                try {
                    mqttAndroidClient.disconnect();
                    mqttAndroidClient.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }
    @Subscribe()
    private void showMessage(String text) {
        Message message = new Message();
        message.obj = text;
        uiHandler.sendMessage(message);
    }

    @Subscribe (threadMode = ThreadMode.MAIN)
    public void Event(String s){

    }

    protected Handler uiHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            // 推应用消息
//            NotificationUtils.show(((ApplicationData) getApplication()).getMainContext(), msg.obj.toString());
//            super.handleMessage(msg);
        }

    };

}
